using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiTest.Api.Db;
using ApiTest.Api.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using ApiTest.Api.Utils;
using System.Text;
using ApiTest.Api.Params;


namespace ApiTest.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
       private readonly string _allowCors="AllowAllCores";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
             // 注入跨域
              services.AddCors(options =>
            {
                options.AddPolicy(_allowCors,
                builder => builder.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin());
            });

             // 注入数据库上下文
            services.AddDbContext<DbInit>(o =>o.UseSqlServer());

            // 注入 IRepository接口及其实现类
            services.AddScoped(typeof(IRepository<>),typeof(EfRepository<>));

            //配置token验证的设置
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(option =>
            {
                 //RequireHttpsMetadata: 限定认证操作是否必须通过https来做,这里不需要，所以false
                    option.RequireHttpsMetadata = false;
                    ////SaveToken: 决定Token在认证完成后，是否需要保存到上下文里并向后传 
                    option.SaveToken = true;

                    var tokenParameter = Configuration.GetSection("TokenParameter").Get<TokenParameter>();

                    option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret)),
                            ValidIssuer = tokenParameter.Issuer,
                            ValidateIssuer = true,
                            ValidateAudience = false,
                             ClockSkew = TimeSpan.Zero,        //就是这一行
                    };
            });
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
        
        //注册验证token的中间件
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseRouting();
             // 注册跨域中间件
            app.UseCors(_allowCors);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
